#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <pthread.h>

//定义全局变量要接受或者发送的数据
char name[20];//姓名
char buf[255];//消息 
char buff[255]; 
int sockfd;//链接标识

//该线程发送消息
void* message(void* arg)
{
	while(1)
	{
		int ret = recv(sockfd,buf,sizeof(buf),0);
		if(0 > ret)
		{
			perror("recv");
			return;
		}
		printf("recv word:%s\n",buf);
	}	
}


//主函数线程负责发送消息
int main(int argc,char* argv[])
{
	if(3 != argc)
	{
		perror("argc");
		return -1;
	}

	//创建一个socket对象
	sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(0 > sockfd)
	{
		perror("socket");
		return -1;
	}

	//创建网络通信对象
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(atoi(argv[1]));
	addr.sin_addr.s_addr = inet_addr(argv[2]);

	//链接目标电脑
	int ret = connect(sockfd,(struct sockaddr*)&addr,sizeof(addr));
	if(ret < 0)
	{
		perror("connect");
		return -1;
	}


	printf("请输入你的名字：");
	gets(name);
	send(sockfd,name,strlen(name),0);


	pthread_t tid = 0;
	int ret1 = pthread_create(&tid,NULL,message,NULL);
	if(0 > ret1)
	{
		perror("pthread_creat");
		return -1;
	}

	while(1)
	{
		printf("send word:");
		gets(buff);
		send(sockfd,buff,strlen(buff),0);
		if(0 == strcmp(buf,"q"))
		{
			printf("%s,您已经退出了悟空聊天室\n",name);
			return 0;
		}
	}
		
	

}

